using System.Globalization;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Blazor;
using Blazor.Core;
using Blazor.Services.AppSetting;
using Blazor.Services.Device;
using Blazor.Services.Update;
using Blazor.Util;
using Blazor.ViewModels.Debug;
using Blazor.ViewModels.DeviceList;
using Blazor.ViewModels.UpdateSetting;
using Microsoft.JSInterop;
using ReactiveUI;

var builder = WebAssemblyHostBuilder.CreateDefault(args);

var httpClient = new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) };
builder.Services.AddScoped(sp => httpClient);

var settingFileName = $"appsettings.{builder.HostEnvironment.Environment}.json";
using var response = await httpClient.GetAsync(settingFileName);
await using var stream = await response.Content.ReadAsStreamAsync();
builder.Configuration.AddJsonStream(stream);
builder.Configuration.AddInMemoryCollection(new List<KeyValuePair<string, string?>>
{
    new("TencentCloud:SecretId", "AKIDwkOq471jHexHSUPAlDWghaXLzTlusgKo"),
    new("TencentCloud:SecretKey", "UlsohQ2ZCPXSDnJepocGj185q5NAqPsD"),
});

var appSetting = new AppSetting(builder.Configuration);

builder.Services.AddSingleton(appSetting);
builder.Services.AddSingleton<IUpdateService, UpdateService>();
builder.Services.AddSingleton<IDeviceService, DeviceService>();
builder.Services.AddScoped<UpdateSettingViewModel>();
builder.Services.AddScoped<DeviceListViewModel>();
builder.Services.AddScoped<DebugUIViewModel>();

builder.Services.AddInteractiveStringLocalizer();
builder.Services.AddLocalization();
builder.Services.AddAntDesign();

builder.Logging.SetMinimumLevel(LogLevel.Information);

builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

var host = builder.Build();

var js = host.Services.GetRequiredService<IJSRuntime>();
var result = await js.InvokeAsync<string>("blazorCulture.get");
var culture = CultureInfo.GetCultureInfoByIetfLanguageTag(string.IsNullOrWhiteSpace(result) ? "en" : result);
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;

var rxExceptionLogger = host.Services.GetRequiredService<ILogger<RxExceptionHandler>>();
RxApp.DefaultExceptionHandler = new RxExceptionHandler(rxExceptionLogger);

await host.RunAsync();